package com.web.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.web.entity.Admin;
import com.web.entity.Token;
import com.web.mapper.AdminMapper;
import com.web.param.AdminLoginDto;
import com.web.param.UpdatePasswordDto;
import com.web.service.IAdminService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.web.service.ITokenService;
import com.web.util.LoginException;
import com.web.util.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.security.provider.MD5;
import sun.security.rsa.RSASignature;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hgjxyz
 * @since 2020-11-18
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired private ITokenService tokenService;

    @Override
    public String adminLogin(AdminLoginDto dto) throws ServiceException {
        Wrapper<Admin> wrapper = new EntityWrapper<>();
        wrapper.eq("username", dto.getUsername());
        Admin admin = this.selectOne(wrapper);
        if(admin == null) throw new ServiceException("未找到当前账号");
        String password = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        if(!password.equals(admin.getPassword()))throw new ServiceException("密码错误");
        return this.tokenService.addToken(admin.getId(), 1);
    }

    @Override
    public void updatePwd(UpdatePasswordDto dto) throws ServiceException, LoginException {
        Token token = this.tokenService.getByToken(dto.getToken());
        if(token.getTheType() == 0) throw new ServiceException("权限不足");
        Admin admin = this.selectById(token.getId());
        if(admin == null) throw new ServiceException("账号异常");
        String password = DigestUtils.md5DigestAsHex(dto.getOldPwd().getBytes());
        if(!password.equals(admin.getPassword()))throw new ServiceException("旧密码错误");
        admin.setPassword(DigestUtils.md5DigestAsHex(dto.getNewPwd().getBytes()));
        if(!this.updateById(admin))throw new ServiceException("修改失败");
    }
}
